from django.shortcuts import render
from rest_framework import serializers
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView
from django_redis import get_redis_connection
# Create your views here.
from goods.models import SKU
from decimal import Decimal

from orders.models import OrderGoods, OrderInfo
from orders.utils import PageNum
from orders.serializers import OrderSerialzier, OrderSaveSerializes, OrderListSerializer
from users.models import User


class OrderShowView(APIView):
    """
        获取订单商品信息
    """

    def get(self, request):

        # 1、建立redis连接
        conn = get_redis_connection('carts')
        # 2、获取用户
        user = request.user
        # 3、获取hash sku_id和count
        sku_id_count = conn.hgetall('cart_%s' % user.id)  # {16:2}
        cart = {}
        for sku_id, count in sku_id_count.items():
            cart[int(sku_id)] = int(count)
        # 4、获取set集合
        sku_ids = conn.smembers('cart_selected_%s' % user.id)
        # 5、根据集合中的sku_id获取商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        # 6、给商品数据对象添加 count
        for sku in skus:
            sku.count = cart[sku.id]
        # 7、指定运费
        freight = Decimal(10.00)
        # 8、序列化返回
        ser = OrderSerialzier({'freight': freight, 'skus': skus})

        return Response(ser.data)



class OrderSaveView(CreateAPIView):
    """
        保存订单
    """
    serializer_class = OrderSaveSerializes

class OrderListView(ListAPIView):
    """
    获取订单列表
    """
    serializer_class = OrderListSerializer

    permission_classes = [IsAuthenticated]
    pagination_class = PageNum  # 分页属性
    filter_backends = [OrderingFilter]  # 过滤排序属性
    ordering_fields = ('create_time', )

    def get_queryset(self):
        user = self.request.user
        try:
            queryset = OrderInfo.objects.filter(user_id = user.id)
        except:
            return Response({"error":"没有该用户"})
        else:
            return queryset





